/*
 * Copyright (C) 2009 Rafael Fernandes
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.phonebooksharing.android.activities.contacts;

import java.io.IOException;
import java.util.ArrayList;

import android.app.ExpandableListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.TextView;

import com.phonebooksharing.android.R;
import com.phonebooksharing.android.activities.contacts.ContactBrowserListView.ViewHolder;
import com.phonebooksharing.android.util.ContactUtils;
import com.phonebooksharing.android.util.Global;
import com.phonebooksharing.android.util.NetworkHandlerTask;
import com.phonebooksharing.dto.friend.ContactItem;
import com.phonebooksharing.dto.friend.GroupItem;

public class ContactBrowserByGroupActivity extends ExpandableListActivity {
    
    private BrowserAdapter adapter;
    public static final String IS_FAVORITE = "f";
    private boolean isFavorite;
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.list_layout_expand_with_empty);

        ExpandableListView lv = getExpandableListView();
        lv.setDivider(getResources().getDrawable(R.drawable.black_bar));

        isFavorite = getIntent().getBooleanExtra(IS_FAVORITE, false);
        
        TextView v = (TextView)LayoutInflater.from(this).inflate(R.layout.header_single_text_layout, null);
        if(isFavorite) {
            v.setText("Navigating by: Favorites");
        } else {
            v.setText("Navigating by: Contacts X Groups");
        }
        lv.addHeaderView(v, null, false);
        
        new LoadDataTask(this).execute();
    }
    
    @Override
    public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
        ContactItem ci = (ContactItem)adapter.getChild(groupPosition, childPosition);
       
        Intent i = new Intent(ContactBrowserByGroupActivity.this, ContactBrowserActivity.class);
        i.putExtra(ContactBrowserActivity.FRIEND_ITEM, ci);
        startActivity(i);
        
        return super.onChildClick(parent, v, groupPosition, childPosition, id);
    }

    class LoadDataTask extends NetworkHandlerTask<Void, ArrayList<GroupItem>, Void> {
        private ProgressDialog progress;
        private Context cx;
        
        LoadDataTask(Context c) {
            cx = c;
        }
        
        @Override
        public void onPreExecute() {
            progress = new ProgressDialog(cx);
            progress.setMessage("Please wait while we load contacts...");
            progress.setIndeterminate(true);
            progress.setCancelable(true);
            progress.show();
        }

        @SuppressWarnings("unchecked")
        @Override
        public Void doInBackground(Void... params) {
            try {
                final String ac;
                if(isFavorite) {
                    ac = "fb";
                } else {
                    ac = "gb";
                }
                final String url = String.format(Global.CONTACT_SERVLET_URL, ac /*ac*/, "" /*p*/, ""/*ps*/, ""/*c*/, "" /*a*/);
                ArrayList<GroupItem> list = (ArrayList<GroupItem>)doNetworkPost(url, Global.authItem);
                publishProgress(list);
            } catch (IOException e) {
                Log.e(Global.LOG_TAG, "are you connected to internet???"); //TODO: send it to user
                e.printStackTrace();
                cancel(true);
            } catch (Exception e) {
                // TODO: handle exception
                e.printStackTrace();
                cancel(true);
            }
            return null;
        }
        
        @Override
        protected void onProgressUpdate(ArrayList<GroupItem>... values) {
            super.onProgressUpdate(values);
            ArrayList<GroupItem> list = values[0];
            adapter = new BrowserAdapter(getApplicationContext(), values[0]);
            setListAdapter(adapter);

            if(list.size() > 0) {
//                adapter = new BrowserAdapter(getApplicationContext(), values[0]);
//                setListAdapter(adapter);
                getExpandableListView().expandGroup(0);
            } else {
                View emptyView = findViewById(android.R.id.empty);
                ((TextView)emptyView.findViewById(android.R.id.text1)).setText("There is no contact to be shown here...");
                getExpandableListView().setEmptyView(emptyView);
            }
//            ((BaseExpandableListAdapter)getExpandableListAdapter()).notifyDataSetChanged();
            adapter.notifyDataSetInvalidated();
        }

        @Override
        public void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);
            progress.dismiss();
        }
    }
    
    class BrowserAdapter extends BaseExpandableListAdapter {
        protected ArrayList<GroupItem> groups;
        protected LayoutInflater inflater;
        public BrowserAdapter(Context cx, ArrayList<GroupItem> g) {
            this.groups = g;
            inflater = (LayoutInflater)cx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }

        @Override
        public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View cv, ViewGroup parent) {
            ViewHolder holder;
            if (cv == null) {
                cv = inflater.inflate(R.layout.list_item_3lines, null);

                holder = new ViewHolder();
                holder.icon = (ImageView) cv.findViewById(android.R.id.icon);
                holder.border = cv.findViewById(android.R.id.background);
                holder.name = (TextView) cv.findViewById(android.R.id.text1);
                holder.time = (TextView) cv.findViewById(R.id.text2);
                holder.status = (TextView) cv.findViewById(R.id.text3);
                holder.location = (TextView) cv.findViewById(R.id.text4);
                
                cv.setTag(holder);
            } else {
                holder = (ViewHolder) cv.getTag();
            }
            
            final ContactItem cache = (ContactItem)getChild(groupPosition, childPosition);
            ContactUtils.setContactPhoto(getExpandableListView(), cache, holder.icon, holder.border, groupPosition, childPosition);
            
            holder.name.setText(cache.name);
            holder.status.setText(cache.status);
            holder.location.setText(cache.location);
            
            return cv;
        }
        
        @Override
        public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
            if (convertView == null)
                convertView = inflater.inflate(R.layout.exp_2column, parent, false);

            GroupItem group = (GroupItem) this.getGroup(groupPosition);
            ((TextView) convertView.findViewById(android.R.id.text1)).setText(group.name);
           
            int size = getChildrenCount(groupPosition);
            if(size > 0) {
                ((TextView) convertView.findViewById(android.R.id.text2)).setText("(" + size + " items)");
            }

            return convertView;
        }

        @Override
        public Object getChild(int groupPosition, int childPosition) {
            return groups.get(groupPosition).contacts.get(childPosition);
        }

        @Override
        public long getChildId(int arg0, int arg1) {
            return 0;
        }

        @Override
        public int getChildrenCount(int groupPosition) {
            return groups.get(groupPosition).contacts.size();
        }

        @Override
        public Object getGroup(int groupPosition) {
            return groups.get(groupPosition);
        }

        @Override
        public int getGroupCount() {
            return groups.size();
        }

        @Override
        public long getGroupId(int groupPosition) {
            return groupPosition;
        }

        @Override
        public boolean hasStableIds() {
            return true;
        }

        @Override
        public boolean isChildSelectable(int groupPosition, int childPosition) {
            return true;
        }
    }
}
